package leedcode_path.treeNoDE;

public class 二叉树的最近公共祖先 {
    /*
    * 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

百度百科中最近公共祖先的定义为：“对于有根树 T 的两个节点 p、q，最近公共祖先表示为一个节点 x，满足 x 是 p、q 的祖先且 x 的深度尽可能大（一个节点也可以是它自己的祖先）。”*/

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root==p||root==q||root==null) return root;

        TreeNode left=lowestCommonAncestor(root.left,p,q);
        TreeNode right=lowestCommonAncestor(root.right,p,q);

        if (left!=null&&right!=null) return root;

        if (left!=null&&right==null){
            return left;
        }else
            return right;
    }

    /*二叉搜索树的*/
        public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) {

            if (root.val>p.val&&root.val>q.val) return  lowestCommonAncestor2(root.left,p,q);
            else if (root.val<p.val&&root.val<q.val) return  lowestCommonAncestor2(root.right,p,q);
            else return root;



        }

    public static void main(String[] args) {
        二叉树的最近公共祖先 a= new 二叉树的最近公共祖先();
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(5);
        root.right = new TreeNode(1);
        root.left.left = new TreeNode(6);
        root.left.right = new TreeNode(2);
        root.right.left = new TreeNode(0);
        root.right.right = new TreeNode(8);
        root.left.right.left = new TreeNode(7);
        root.left.right.right = new TreeNode(4);
        a.lowestCommonAncestor(root,root.left,root.left.right.right);
    }
}

